$(document).ready(function() {
    loadResultNames();
    loadUploadNames();

    $('#compareBtn').click(startComparison);
});

function loadResultNames() {
    $.ajax({
        url: '/amino/result-names',
        method: 'GET',
        success: function(data) {
            $('#resultName').empty();
            data.forEach(function(name) {
                $('#resultName').append($('<option>', {
                    value: name,
                    text: name
                }));
            });
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('Error loading result names:', textStatus, errorThrown);
        }
    });
}

function loadUploadNames() {
    $.ajax({
        url: '/amino/upload-names',
        method: 'GET',
        success: function(data) {
            $('#uploadName').empty();
            data.forEach(function(name) {
                $('#uploadName').append($('<option>', {
                    value: name,
                    text: name
                }));
            });
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('Error loading upload names:', textStatus, errorThrown);
        }
    });
}

function startComparison() {
    var resultName = $('#resultName').val();
    var uploadName = $('#uploadName').val();
    var tolerance = $('#tolerance').val();
    var comparisonName = $('#comparisonName').val();

    if (!resultName || !uploadName || !tolerance || !comparisonName) {
        alert('请选择结果名称、上传名称，输入容差值和对比名称');
        return;
    }

    $('.progress').show();
    $('#progressBar').css('width', '0%').text('0%');

    $.ajax({
        url: '/amino/compare',
        method: 'POST',
        data: JSON.stringify({
            resultName: resultName,
            uploadName: uploadName,
            tolerance: tolerance,
            comparisonName: comparisonName
        }),
        contentType: 'application/json',
        success: function(data) {
            updateProgress(data.jobId);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('Error starting comparison:', textStatus, errorThrown);
            alert('启动比较时出错：' + textStatus);
        }
    });
}

function updateProgress(jobId) {
    $.ajax({
        url: '/amino/compare/progress/' + jobId,
        method: 'GET',
        success: function(data) {
            $('#progressBar').css('width', data.progress + '%').text(data.progress + '%');
            if (data.progress < 100) {
                setTimeout(function() {
                    updateProgress(jobId);
                }, 1000);
            } else {
                alert('对比完成');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('Error updating progress:', textStatus, errorThrown);
        }
    });
}